package com.sj.client;

import com.sj.pojo.MsgTypeEnum;
import com.sj.pojo.Protocol;
import com.sj.utils.TransferUtils;
import lombok.AllArgsConstructor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-07-07
 * Time: 下午 12:04
 * Description: 客户端读线程
 *
 * @author xiaoqi
 * @since 2022-07-07
 */
@AllArgsConstructor
public class ClientThread implements Runnable {

    private Selector selector;


    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        for (; ; ) {
            try {
                int requestCount = selector.select();
                if (requestCount == 0) {
                    continue;
                }
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()) {
                        readOperation(selector, selectionKey);
                    }
                    iterator.remove();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void readOperation(Selector selector, SelectionKey selectionKey) {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        try {
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);

            Protocol res = TransferUtils.receive(socketChannel);
            if("bye".equalsIgnoreCase(res.getContent())){
                socketChannel.close();
                selector.close();
            }
            System.out.println("消息类型：" + res.getHeader().getMsgType() + " 消息长度： " + res.getHeader().getMsgLen() + " 消息内容： " + res.getContent());
        } catch (IOException e) {
            System.out.println("有连接断开client read");
        }

    }

}